package com.ruoyi.verify.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.verify.domain.*;
import com.ruoyi.verify.exception.verifyPlanException;
import com.ruoyi.verify.mapper.VerifyPlanInfoMapper;
import com.ruoyi.verify.mapper.VerifyRequirementMapper;
import com.ruoyi.verify.mapper.VerifyTemplateMapper;
import com.ruoyi.verify.service.IVerifyPlanInfoService;
import com.ruoyi.verify.transform.VerifyPlanInfos;
import com.ruoyi.verify.transform.VerifyPlanMemberInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class VerifyPlanInfoServiceImpl implements IVerifyPlanInfoService
{
    @Autowired
    private VerifyPlanInfoMapper verifyPlanInfoMapper;

    @Autowired
    private VerifyRequirementMapper verifyRequirementMapper;

    @Autowired
    private VerifyTemplateMapper verifyTemplateMapper;




    /**
     * 查询【请填写功能名称】
     *
     * @param planid 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public VerifyPlanInfo selectVerifyPlanInfoById(Long planid)
    {
        return verifyPlanInfoMapper.selectVerifyPlanInfoById(planid);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param verifyPlanInfo 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<VerifyPlanInfo> selectVerifyPlanInfoList(VerifyPlanInfo verifyPlanInfo)
    {
        return verifyPlanInfoMapper.selectVerifyPlanInfoList(verifyPlanInfo);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param verifyPlanInfo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertVerifyPlanInfo(VerifyPlanInfo verifyPlanInfo)
    {
        return verifyPlanInfoMapper.insertVerifyPlanInfo(verifyPlanInfo);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param verifyPlanInfo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateVerifyPlanInfo(VerifyPlanInfo verifyPlanInfo)
    {
        return verifyPlanInfoMapper.updateVerifyPlanInfo(verifyPlanInfo);
    }

    /**
     * 删除【请填写功能名称】对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteVerifyPlanInfoByIds(String ids)
    {
        return verifyPlanInfoMapper.deleteVerifyPlanInfoByIds(Convert.toStrArray(ids));
    }


    /**
     * 删除【请填写功能名称】信息
     *
     * @param planid 【请填写功能名称】ID
     * @return 结果
     */
    public int deleteVerifyPlanInfoById(Long planid)
    {
        return verifyPlanInfoMapper.deleteVerifyPlanInfoById(planid);
    }

    @Override
    public int addVerifyMember(Long planid, Long memberid, String moudlecode) {
        return verifyPlanInfoMapper.addVerifyMember(planid,memberid,moudlecode);
    }

    @Override
    public List<VerifyPlanInfo> selectVerifyPlanInfoByParentId(Long planid) {
        return verifyPlanInfoMapper.selectVerifyPlanInfoByParentId(planid);
    }

    @Override
    public List<VerifyPlanInfo> selectVerifyPlanMemberMoudle(Long planid) {
        return verifyPlanInfoMapper.selectVerifyPlanMemberMoudle(planid);
    }

    @Override
    public void saveCurrentPlan(VerifyPlanMemberInfo verifyPlanMemberInfo) {
        VerifyPlanInfo verifyPlanInfo = verifyPlanMemberInfo.getVerifyPlanInfo();
        verifyPlanInfoMapper.updateVerifyPlanInfo(verifyPlanInfo);

        Long parentid = verifyPlanInfo.getPlanid();
        verifyPlanInfoMapper.deleteVerifyPlanMemberMoudleById(parentid);
        verifyPlanMemberInfo.getVerifyPlanInfos().stream().forEach(vpi -> {
            String categorys = StringUtils.join(vpi.getSupplycategorys(), ",");
//            String category = categorys.substring(1,categorys.length()-1);
            vpi.setSupplycategory(categorys);
            VerifyRequirement verifyRequirement = new VerifyRequirement();
            verifyPlanInfoMapper.updateVerifyPlanInfo(vpi);//保存每项计划内容
//            verifyRequirement.setPlanid(parentid);
//            verifyRequirement.setRequirementid(vpi.getVerifyrequirementid());
//            verifyRequirementMapper.updateVerifyRequirement(verifyRequirement);//绑定需求和计划关系
        });


        if(verifyPlanMemberInfo.getVerifyplanmembermoudle()!=null){
            //计划组人员
            verifyPlanMemberInfo.getVerifyplanmembermoudle().stream().forEach(vpmm -> {
                vpmm.getMoudlecodes().forEach(m -> {
                    verifyPlanInfoMapper.addVerifyMember(parentid,vpmm.getMemberid(),m);
                });
            });
        }
    }

    @Override
    public List<VerifyPlanInfo> selectMyVerifyPlanInfoList(VerifyPlanInfo verifyPlanInfo,List<Long> verifyplanid) {
        if(verifyplanid.size()==0){
            return null;
        }
        verifyPlanInfo.setPlanids(verifyplanid);

        return verifyPlanInfoMapper.selectMyVerifyPlanInfoList(verifyPlanInfo);
    }

    @Override
    public List<Long> selectMyVerifyPlanList(VerifyPlanInfo verifyPlanInfo, String memberid) {
        String oaid = verifyPlanInfoMapper.selectOaidByUserId(Long.parseLong(memberid));
        return verifyPlanInfoMapper.selectMyVerifyPlanList(Long.parseLong(oaid)).stream().map(vp -> vp.getPlanid()).collect(Collectors.toList());
    }

//    @Override
//    public List<Long> selectMyVerifyPlanList(VerifyPlanInfo verifyPlanInfo, String memberid) {
//        return verifyPlanInfoMapper.selectMyVerifyPlanList(Long.parseLong(memberid)).stream().map(vp -> vp.getPlanid()).collect(Collectors.toList());
//    }

    @Override
    public boolean isgroupleader(Long memberid, Long planid) {
        String oaid = verifyPlanInfoMapper.selectOaidByUserId(memberid);
        return verifyPlanInfoMapper.isgroupleader(Long.parseLong(oaid),planid);
    }
//    @Override
//    public boolean isgroupleader(Long memberid, Long planid) {
//        return verifyPlanInfoMapper.isgroupleader(memberid,planid);
//    }

    @Override
    public Map<String, Object> createVerifyPlanByRequirementIds(List<Long> verifyrequirementids) {
        if(verifyrequirementids.size()==0){
            return null;
        }
        String memberid = ServletUtils.getRequest().getHeader(Constants.CURRENT_ID);
        String username = verifyPlanInfoMapper.selectUserNameByUserId(Long.parseLong(memberid));
        Map<String,Object> map = new HashMap<>();
        VerifyPlanInfo parentVerifyPlanInfo = new VerifyPlanInfo();
        parentVerifyPlanInfo.setParentid(-1l);

        verifyPlanInfoMapper.insertVerifyPlanInfo(parentVerifyPlanInfo);
        StringBuilder stringBuilder = new StringBuilder();
        List<VerifyPlanInfo> verifyPlanInfos = new ArrayList<>();
        for(Long vri: verifyrequirementids){
            VerifyRequirement verifyRequirement = verifyRequirementMapper.selectVerifyRequirementById(vri);
            VerifyPlanInfo verifyPlanInfo = new VerifyPlanInfo();
            verifyPlanInfo.setParentid(parentVerifyPlanInfo.getPlanid());
            verifyPlanInfo.setFactorycode(verifyRequirement.getFactorycode());
            verifyPlanInfo.setVerifytype(verifyRequirement.getVerifytype());
            verifyPlanInfo.setSuppliername(verifyRequirement.getSuppliername());
            verifyPlanInfo.setSupplycategory(verifyRequirement.getSupplycategory());
            verifyPlanInfo.setVerifyrequirementid(vri);
            verifyPlanInfo.setCreater(username);

            VerifyRequirement ifHaveTemplate = verifyRequirementMapper.selectIfHaveTemplate(verifyRequirement.getVerifytype(), verifyRequirement.getFactorycode());
            if (ifHaveTemplate == null) {
                stringBuilder.append(verifyRequirement.getFactoryname()+" 事业部下的审核类型: " + verifyRequirement.getVerifytype() + " 尚未生成审核模板，请生成模板后再生成计划！!");
                continue;
            }
            verifyPlanInfo.setTemplateid(ifHaveTemplate.getTemplateid());//将模板绑定到子计划中


            verifyPlanInfoMapper.insertVerifyPlanInfo(verifyPlanInfo);
            verifyRequirement.setPlanid(parentVerifyPlanInfo.getPlanid());
            verifyRequirement.setSonplanid(verifyPlanInfo.getPlanid());
            verifyRequirement.setStatus(3l);

            verifyRequirementMapper.updateVerifyRequirement(verifyRequirement);
            verifyPlanInfos.add(verifyPlanInfo);
        }

        map.put("verifyPlanInfos",verifyPlanInfos);
        if (stringBuilder.length()!=0){
            map.put("errMsg",stringBuilder);
            return map;
        }

        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveCurrentPlanInfo(Map<String, Object> map) throws verifyPlanException {

        VerifyPlanInfo mainVerifyPlanInfo = JSON.parseObject(JSON.toJSONString(map.get("verifyPlanInfo")), VerifyPlanInfo.class);
        List<Object> sonObjectList = JSON.parseObject(JSON.toJSONString(map.get("verifyPlanInfos")), List.class);
        List<VerifyPlanInfos> sonVerifyPlanInfoList = sonObjectList.stream().map(sol -> JSON.parseObject(JSON.toJSONString(sol), VerifyPlanInfos.class)).collect(Collectors.toList());
        verifyPlanInfoMapper.updateVerifyPlanInfo(mainVerifyPlanInfo);//保存主计划上基本信息




        sonVerifyPlanInfoList.forEach(svpil -> {
            VerifyPlanInfo vpi = svpil.getVpi();
            List<VerifyTemplate> verifyTemplates = new ArrayList<>();
            List<VerifyTemplate> son_Ep6 = null;
            List<VerifyTemplate> Ep6 = null;

            if(vpi.getVerifytype().contains("VDA6.3")){//VDA6.3中，选中P6则默认选中P6下所有子模块
                verifyTemplates = verifyTemplateMapper.selectVerifyTemplateClassNew(vpi.getVerifytype(), vpi.getFactorycode());
                son_Ep6 = verifyTemplates.stream().filter(v -> v.getContent().startsWith("6.")).collect(Collectors.toList());
                Ep6 = verifyTemplates.stream().filter(v -> v.getContent().startsWith("6、")).collect(Collectors.toList());
            }

            List<VerifyPlanInfos.innerVerify> vpmmList = svpil.getVpmm();
            vpmmList.forEach(vpmm ->{
                if(vpmm.getMoudlecodes()==null || vpmm.getMoudlecodes().size()==0){
                    log.error("有人员未分配模块！");
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new verifyPlanException("有人员未分配模块！");
                }
            });


            String categorys = StringUtils.join(vpi.getSupplycategorys(),",");
            vpi.setSupplycategory(categorys);

            if(vpi.getVerifytime()!=null && vpi.getVerifytime().length>1){//设置审核开始和结束时间
                vpi.setVerifystarttime(vpi.getVerifytime()[0]);
                vpi.setVerifyendtime(vpi.getVerifytime()[1]);
            }

//            vpmmList.stream().filter(vpmm -> vpmm.getIsgroupleader().equals("1")).forEach(v -> vpi.setGroupleaderid(v.getMemberid()));
            List<VerifyPlanInfos.innerVerify> teamleader = vpmmList.stream().filter(vpmm -> vpmm.getIsgroupleader().equals("1")).collect(Collectors.toList());
            if(teamleader==null || teamleader.size()==0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new verifyPlanException("每个子计划至少选择一名组长！");
            }
            vpi.setGroupleaderid(teamleader.get(0).getMemberid());
            verifyPlanInfoMapper.updateVerifyPlanInfo(vpi);//保存每个子计划信息

            verifyPlanInfoMapper.deleteVerifyPlanMemberMoudleById(vpi.getPlanid());//修改人员前先删除人员模块关系
            List<VerifyTemplate> finalSon_Ep6 = son_Ep6;
            List<VerifyTemplate> finalEp6 = Ep6;
            vpmmList.forEach(vpmm -> {
                vpmm.getMoudlecodes().forEach(m -> {
                    if(finalSon_Ep6 !=null && m.equals(finalEp6.get(0).getVerifyid())){//如果选中了P6模块，则保存P6下的所有子模块
                        finalSon_Ep6.forEach(f ->{ //此处可不写循环，因为遍历次数少。如果遍历次数多，不建议这么写
                            verifyPlanInfoMapper.addVerifyMember(vpi.getPlanid(),vpmm.getMemberid(),f.getVerifyid());
                        });
                    }
                    verifyPlanInfoMapper.addVerifyMember(vpi.getPlanid(),vpmm.getMemberid(),m);//保存人员和模块关系
                });
            });
        });

        return mainVerifyPlanInfo.getPlanid();

    }

    @Override
    public Set<String> selectPermsByUserId(Long userId) {
        return verifyPlanInfoMapper.selectPermsByUserId(userId);
    }

    @Override
    public String selectUserNameByUserId(Long userId) {
        return verifyPlanInfoMapper.selectUserNameByUserId(userId);
    }

//    @Override
//    public Map<String, Object> getPlanInfoById(Long verifyPlanId) {
//
//    }


}
